package me.spring.cloud.common.components.mds.dynamic;

import me.spring.cloud.common.components.mds.util.DataSourceSet;
import java.util.Map;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * 动态数据源
 */
@Slf4j
public final class DynamicDataSource extends AbstractRoutingDataSource {

  public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
    super.setDefaultTargetDataSource(defaultTargetDataSource);
    super.setTargetDataSources(targetDataSources);
    super.afterPropertiesSet();
  }

  @Override
  protected Object determineCurrentLookupKey() {
    String keyDataSource = DataSourceSet.getCurrDataSource();
    log.debug("***当前数据源为[{}]", keyDataSource == null ? "默认数据源" : keyDataSource);
    return keyDataSource;
  }
}
